package com.vipyinzhiwei.android;

import android.app.ActivityManager;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Process;
import android.os.StrictMode;
import android.support.multidex.MultiDex;
import android.text.TextUtils;

import com.squareup.leakcanary.LeakCanary;
import com.squareup.leakcanary.RefWatcher;
import com.umeng.commonsdk.UMConfigure;
import com.umeng.socialize.PlatformConfig;
import com.vipyinzhiwei.android.common.MyIActivityImpl;
import com.vipyinzhiwei.android.common.MyIFragmentImpl;
import com.vipyinzhiwei.android.common.MyNetworkListener;
import com.vipyinzhiwei.android.library.Logger;
import com.vipyinzhiwei.android.library.MApplication;
import com.vipyinzhiwei.android.library.base.ui.IActivity;
import com.vipyinzhiwei.android.library.base.ui.IFragment;
import com.vipyinzhiwei.android.library.tools.ToolChannel;
import com.vipyinzhiwei.android.library.tools.ToolData;
import com.vipyinzhiwei.android.library.tools.uipage.UImanagerHelper;
import com.vipyinzhiwei.android.library.umeng.push.UmengPush;
import com.vipyinzhiwei.android.library.umeng.statistics.UmengMobclickAgent;
import com.vipyinzhiwei.android.tools.ToolUmengDevice;

import org.litepal.LitePal;

import java.util.List;

/**
 * vipyinzhiwei全局的Application
 *
 * @author vipyinzhiwei
 * @version 1.0
 */
public class GlobalApplication extends MApplication {
    /**
     * 友盟AppKey
     */
    public static final String UMENG_APPKEY = "5b3c5ff8f29d981f1d000013";
    /**
     * 友盟推送secret,集成Push功能时必须传入Push的secret，否则传空
     */
    public static final String UMENG_PUSH_SECRET = "f40ea8d4b3547b9f0d82a11dd6b038ba";

    /**
     * 内存泄露对象监测
     */
    private RefWatcher refWatcher;

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(base);
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Logger.i("友盟提供>获取设备识别信息:", ToolUmengDevice.getDeviceInfo(this));

        //LitePal数据库初始化
        LitePal.initialize(this);

        //判断当前进程为APP主进程
        if (getPackageName().equals(getCurrentProcessName())) {
            //初始化友盟通用基础库（友盟分享、友盟统计、友盟推送），初始化后，不需要再做重复初始化操作
            UMConfigure.init(this, UMENG_APPKEY, gainChannelId(), UMConfigure.DEVICE_TYPE_PHONE,
                    UMENG_PUSH_SECRET);
            //设置组件化的Log开关。默认为false，如需查看LOG设置为true
            UMConfigure.setLogEnabled(BuildConfig.DEBUG);
            //设置日志加密。默认为false（不加密）
            UMConfigure.setEncryptEnabled(true);

            //请在 sdk 初始化之后调用事件，组件化统计 SDK 仅支持在 APP 主进程中调用事件
            UmengMobclickAgent.config(this, BuildConfig.DEBUG);

            //初始化友盟推送配置
            UmengPush.config(this, BuildConfig.DEBUG);

//          //初始化友盟分享
            registerSharePlatform();

            //启动Service网络监听
            startService(new Intent(this, MyNetworkListener.class));

            //破除高版本Uri限制
            strictMode();
        }

        //初始化友盟推送,请勿在调用register方法时做进程判断处理
        UmengPush.registerPush(this);

        installLeakCanary(this);
    }

    /**
     * 破除高版本Uri限制 FileUriExposedException
     */
    private void strictMode() {
        StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
        StrictMode.setVmPolicy(builder.build());
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            builder.detectFileUriExposure();
        }
    }

    /**
     * 获取渠道号
     *
     * @return
     */
    public static String gainChannelId() {
        //META-INF文件夹写入的渠道号（美团多渠道打包方案）
        String strMetaInfChannel = ToolChannel.gainChannel(gainContext(), ToolChannel.CHANNEL_KEY);
        if (!TextUtils.isEmpty(strMetaInfChannel)) {
            channelId = strMetaInfChannel;
            return channelId;
        }

        //AndroidManifest.xml配置的渠道号（一般多渠道打包方案）
        String strManifestChannel = ToolData.gainMetaData(gainContext(), GlobalApplication.class,
                "UMENG_CHANNEL");
        if (!TextUtils.isEmpty(strManifestChannel)) {
            channelId = strManifestChannel;
            return channelId;
        }

        return channelId;
    }

    /**
     * 注册分享平台,在UmengShareHelper.initSDK方法之后调用，Application注册即可
     */
    public void registerSharePlatform() {
        PlatformConfig.setWeixin("wxdc1e388c3822c80b", "3baf1193c85774b3fd9d18447d76cab0");
        //豆瓣RENREN平台目前只能在服务器端配置
        PlatformConfig.setSinaWeibo("3607196738", "39c492772d0382323aeb29c1f17a7ba9",
                "https://api.weibo.com/oauth2/default.html");
        PlatformConfig.setQQZone("1107046780", "p47djoUoAhp9qsfw");
    }

    /**
     * 返回当前进程的名称
     *
     * @return the name of current process
     */
    public String getCurrentProcessName() {
        ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        if (am == null) return null;
        List<ActivityManager.RunningAppProcessInfo> info = am.getRunningAppProcesses();
        if (info == null || info.size() == 0) return null;
        int pid = Process.myPid();
        for (ActivityManager.RunningAppProcessInfo aInfo : info) {
            if (aInfo.pid == pid) {
                if (aInfo.processName != null) {
                    return aInfo.processName;
                }
            }
        }
        return "";
    }

    /**
     * 获取内存泄露监测对象
     *
     * @param context
     * @return
     */
    public static RefWatcher getRefWatcher(Context context) {
        GlobalApplication application = (GlobalApplication) context.getApplicationContext();
        return application.refWatcher;
    }

    /**
     * 初始化内存泄露监控
     *
     * @param context
     */
    protected void installLeakCanary(Application context) {
        if (LeakCanary.isInAnalyzerProcess(context)) {
            // This process is dedicated to LeakCanary for heap analysis.
            // You should not init your app in this process.
            return;
        }
        refWatcher = LeakCanary.install(context);
    }

    @Override
    protected void setUiImpl(IActivity sIActivity, IFragment sIFragment) {
        super.setUiImpl(sIActivity, sIFragment);
        //注入Activity生命周期方法管理类，根据业务需求是否实现友盟统计功能。
        UImanagerHelper.setsIActivity(new MyIActivityImpl());
        //注入Fragment生命周期方法管理类，根据业务需求是否实现友盟统计功能
        UImanagerHelper.setsIFragment(new MyIFragmentImpl());
    }

    @Override
    public void exit() {
        super.exit();
        try {
            UmengMobclickAgent.onKillProcess(this);

            //停止Service网络监听
            stopService(new Intent(this, MyNetworkListener.class));

            //关闭所有Activity
            removeAll();
            //退出进程
            System.exit(0);
        } catch (Exception e) {

        }

    }
}
